package cn.kingshion.sort;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class MergeSort {
    public static void main(String[] args) {
//随机化一个大容量的数组。
        //用来测试冒泡排序的效率
        int arr[] = new int[80000];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 80000);
        }

        //定义一个时间对象，用来表示数组排序前的时间
        Date date1 = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("排序前：" + simpleDateFormat.format(date1));
        //排序数组
        int[] temp = new int[arr.length];
        mergeSort(arr,0,arr.length-1,temp);

        System.out.println(Arrays.toString(arr));
        //新的时间，打印出排序完的时间
        Date date2 = new Date();
        System.out.println("排序前：" + simpleDateFormat.format(date2));

    }

    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);

            merge(arr, left, mid, right, temp);
        }
    }

    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int l = left;
        int r = mid+1;
        int t = 0;

        while (l < mid && r < right) {
            if (arr[l] <= arr[r]) {
                temp[t++] = arr[l++];
            } else {
                temp[t++] = arr[r++];
            }
        }

        while (l <= mid) {
            temp[t++] = arr[l++];
        }
        while (r <= right) {
            temp[t++] = arr[r++];
        }

        t = 0;
        int tempLeft = left;
//        System.out.println(tempLeft+"--->"+right);
        while (tempLeft <= right) {
            arr[tempLeft++] = temp[t++];
        }
    }
}
